import React from 'react';
import {DeviceEventEmitter, StatusBar, Linking, TextInput, Easing, Animated, PixelRatio, TouchableOpacity, Alert, Dimensions, StyleSheet, View, Text, Image, Modal } from 'react-native';


import Images from '../../images/Images';
import Constants from '../../utils/Constants';
import screen from '../../utils/screen';
import {getffly} from '../../utils/common';

const imags = [
    Images.order_grab_change1,
    Images.order_grab_change2,
    Images.order_grab_change3
];
const amitime = 500;

const progressWidth = screen.width - screen.PIXEL_240;


const Pixel_322 = screen.scaleSize(322)

class Grabbing extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            modalVisible: false,
            icon1:imags[0],
            iconA1:null,
            icon2:imags[1],
            iconA2:null,
            icon3:null,
            progress:0,
            showtips1:false,
            showtips2:false,
            statetext1:Constants.order.searching_for_merchants,
            statetext2:'.'
        };
        this.textindex = 1;
        this.dqindex1 = 1;
        this.dqindex2 = 0;


        this.dialog = null;
        this.setDialogRef = (element) => {
            this.dialog = element;
        };

        this.maxProgress = 0;
        this.curProgress = 0;


        this.time1 = null;
        this.time2 = null;
        this.isload = false;
        this.fadeAnim1 = new Animated.Value(1);
        this.fadeAnim2 = new Animated.Value(0);

        this.icons = [

        ];
        this.iconIndex = 0;

        this.changeTime1 = 0;
        this.changeTime2 = 0;

        this.transX1 =  new Animated.Value(screen.PIXEL_100);
        this.transX2 =  new Animated.Value(screen.PIXEL_400);
        this.dqtranstype = 0;



    }
    componentDidMount = () => {

    }


    startTimer1 = () => {
        this.time1 && clearInterval(this.time1);
        this.time1 = setInterval(() => {

            this.curProgress  = this.curProgress + 1;
            this.changeTime2 = this.changeTime2 + 1
            if(this.curProgress < this.maxProgress) {
                this.setState({
                    progress:this.curProgress / this.maxProgress,
                    statetext1:Constants.order.searching_for_merchants,
                });
                if(!this.isload && this.changeTime2 >= this.changeTime1) {
                    this.changeTime2 = 0
                    this.changeTime1 = Math.floor(Math.random() * 3 + 2)
                    this.isload = true;
                    this.hideami();
                }
            } else {

                this.time1 && clearInterval(this.time1);

                this.setState({
                    progress:1,
                    showtips1:true,
                    statetext1:Constants.order.searching_for_merchants,
                });
                this.maxProgress = 5 + Math.floor(Math.random()*21);
                this.curProgress = 0;
                console.log("this.maxProgress",this.maxProgress);
                this.startTimer2();
            }
        }, 300);
    }

    startTimer2 = () => {
        var self = this;
        this.time2 && clearInterval(this.time2);
        this.time2 = setInterval(() => {
            this.curProgress  = this.curProgress + 1;
            this.changeTime2 = this.changeTime2 + 1
            if(this.curProgress < this.maxProgress)
            {
                this.setState({
                    progress:this.curProgress / this.maxProgress,
                    statetext1:Constants.order.matching_products,
                });

                if(!this.isload && this.haveusing.length > 0) {

                    if(this.maxProgress - this.curProgress > 3 && this.changeTime2 >= this.changeTime1  ) {
                        this.changeTime2 = 0
                        this.changeTime1 = Math.floor(Math.random() * 3 + 1)
                        this.isload = true;
                        this.hideami();
                    } else if(this.maxProgress - this.curProgress <= 3) {

                        if(this.dqtranstype === 0) {
                            if(this.state.iconA1 != this.chooose) {
                                this.setState({
                                    iconA1:this.haveusing[0],
                                });
                                this.isload = true;
                                this.hideami();
                            }
                        } else if(this.dqtranstype === 1) {
                            if(this.state.iconA2 != this.chooose)
                            {
                                this.setState({
                                    iconA2:this.haveusing[0],
                                });
                                this.isload = true;
                                this.hideami();
                            }
                        }
                    }
                }
            }
            else {
                this.time2 && clearInterval(this.time2);

                if(!this.isload)
                {
                    this.setState({
                        progress:1.0,
                        showtips2:true,
                    });
                }
                else
                {
                    this.setState({
                        progress:1.0,
                        showtips2:true,
                    });
                }
                setTimeout(()=>{
                    self.time3 && clearInterval(this.time3);
                    self.setState({
                        statetext1:Constants.order.placing_order,
                        statetext2:'...',
                    });
                },300)
                setTimeout(()=>{
                    self.hideDialog();
                    this.callback && this.callback()
                    // DeviceEventEmitter.emit("grab_end", "");
                },1000)
            }
        }, 300);
    }
    startTimer3 = () => {

        this.time3 && clearInterval(this.time3);
        this.time3 = setInterval(() => {

            var str1 = ".";
            if(this.textindex == 1)
            {
                str1 = ".";
            }
            else if(this.textindex == 2)
            {
                str1 = "..";
            }
            else if(this.textindex == 3)
            {
                str1 = "...";
            }
            this.setState({
                statetext2:str1
            })
            this.textindex = this.textindex + 1;
            if(this.textindex > 3)
            {
                this.textindex = 0;
            }
        }, 200);
    }

    hideami() {
        console.log('hide ami')
        var self = this;

        let tranxValue1 = -Pixel_322;
        let tranxValue2 = screen.PIXEL_100;
        let fadeValue1 = 0
        let fadeValue2 = 1
        if(this.dqtranstype === 0){
            this.transX1.stopAnimation();
            Animated.timing(this.transX1, {
                toValue: tranxValue1,
                duration: amitime,
                useNativeDriver: false,
                // easing: Easing.linear
            }).start(()=>{
                self.transX1.stopAnimation();
                self.transX1 =  new Animated.Value(screen.PIXEL_400);
                self.dqtranstype = 1
            })

            this.transX2.stopAnimation();
            Animated.timing(this.transX2, {
                toValue: tranxValue2,
                duration: amitime,
                useNativeDriver: false,
                // easing: Easing.linear
            }).start(()=>{

            })

            this.fadeAnim1.stopAnimation();
            Animated.timing(this.fadeAnim1, {
                toValue: fadeValue1,
                duration: amitime,
                useNativeDriver: false,
                easing: Easing.out(Easing.exp)
            }).start(()=>{
                this.changeImage()
            })
            this.fadeAnim2.stopAnimation();
            Animated.timing(this.fadeAnim2, {
                toValue: fadeValue2,
                duration: amitime,
                useNativeDriver: false,
                easing: Easing.in(Easing.exp)
            }).start(()=>{

            })

        }else{
            tranxValue1 = screen.PIXEL_100
            tranxValue2 = -Pixel_322
            fadeValue1 = 1
            fadeValue2 = 0

            this.transX1.stopAnimation();
            Animated.timing(this.transX1, {
                toValue: tranxValue1,
                duration: amitime,
                useNativeDriver: false,
                // easing: Easing.linear
            }).start(()=>{

            })

            this.transX2.stopAnimation();
            Animated.timing(this.transX2, {
                toValue: tranxValue2,
                duration: amitime,
                useNativeDriver: false,
                // easing: Easing.linear
            }).start(()=>{
                self.transX2.stopAnimation();
                self.transX2 =  new Animated.Value(screen.PIXEL_400);
                self.dqtranstype = 0
            })

            this.fadeAnim1.stopAnimation();
            Animated.timing(this.fadeAnim1, {
                toValue: fadeValue1,
                duration: amitime,
                useNativeDriver: false,
                easing: Easing.out(Easing.exp)
            }).start(()=>{

            })

            this.fadeAnim2.stopAnimation();
            Animated.timing(this.fadeAnim2, {
                toValue: fadeValue2,
                duration: amitime,
                useNativeDriver: false,
                easing: Easing.in(Easing.exp)
            }).start(()=>{
                this.changeImage2()
            })
        }



    }

     changeImage = ()=>{
        let self = this
        if(self.state.showtips1)
        {
            if(self.haveusing.length > 0)
            {
                if(self.dqindex2 > self.haveusing.length - 1)
                {
                    self.dqindex2 = 0;
                }
                self.setState({
                    iconA1: self.haveusing[self.dqindex2]
                },()=>{
                    self.dqindex2 = self.dqindex2 + 1;
                    self.isload = false;
                });
            }
            else
            {
                self.dqindex1 = self.dqindex1 + 1;
                if(self.dqindex1 > imags.length - 1)
                {
                    self.dqindex1 = 0;
                }
                self.setState({
                    icon1:imags[self.dqindex1]
                },()=>{
                    self.isload = false;
                });
            }
        }
        else
        {
            self.dqindex1 = self.dqindex1 + 1;
            if(self.dqindex1 > imags.length - 1)
            {
                self.dqindex1 = 0;
            }
            self.setState({
                icon1:imags[self.dqindex1]
            },()=>{
                self.isload = false;
            });
        }
    }

    changeImage2 = ()=>{
        let self = this
        if(self.state.showtips1)
        {
            if(self.haveusing.length > 0)
            {
                if(self.dqindex2 > self.haveusing.length - 1)
                {
                    self.dqindex2 = 0;
                }
                self.setState({
                    iconA2:self.haveusing[self.dqindex2]
                },()=>{
                    self.dqindex2 = self.dqindex2 + 1;
                    self.isload = false;
                });
            }
            else
            {
                self.dqindex1 = self.dqindex1 + 1;
                if(self.dqindex1 > imags.length - 1)
                {
                    self.dqindex1 = 0;
                }
                self.setState({
                    icon2:imags[self.dqindex1]
                },()=>{
                    self.isload = false;
                });
            }
        }
        else
        {
            self.dqindex1 = self.dqindex1 + 1;
            if(self.dqindex1 > imags.length - 1)
            {
                self.dqindex1 = 0;
            }
            self.setState({
                icon2:imags[self.dqindex1]
            },()=>{
                self.isload = false;
            });
        }
    }

    hideDialog = () => {
        this.time1 && clearInterval(this.time1);
        this.time2 && clearInterval(this.time2);
        this.time3 && clearInterval(this.time3);
        this.setState({ modalVisible: false });
    }

    showDialog = (icons,callback ) => {

        this.callback = callback
        this.textindex = 1;
        this.dqindex1 = 1;
        this.dqindex2 = 0;

        this.maxProgress = 0;
        this.curProgress = 0;
        this.changeTime1 = 0
        this.changeTime2 = 0

        this.time1 = null;
        this.time2 = null;
        this.isload = false;
        this.fadeAnim1 = new Animated.Value(1);
        this.fadeAnim2 = new Animated.Value(0);

        this.icons = icons;
        this.iconIndex = 0;

        this.haveusing = [];

        this.chooose = this.icons[0];
        this.transX1 =  new Animated.Value(screen.PIXEL_100);
        this.transX2 =  new Animated.Value(screen.PIXEL_400);
        this.dqtranstype = 0;

        this.setState({
            modalVisible: true,
            icon1:imags[0],
            icon2:imags[1],
            iconA1:null,
            iconA2:null,
            icon3:this.icons[0],
            progress:0,
            showtips1:false,
            showtips2:false,
            statetext1:Constants.order.searching_for_merchants,
            statetext2:'.'
        },()=>{

            this.maxProgress = 5 + Math.floor(Math.random()*21);

            console.log("this.maxProgress",this.maxProgress);
            this.curProgress = 0;
            this.startTimer1();
            this.startTimer3();
        });
    }
    render() {

        const {showtips1,showtips2} = this.state
        return (
            <Modal
                animationType={'none'}
                transparent={true}
                visible={this.state.modalVisible}
                onRequestClose={() => {
                    this.hideDialog()
                }}
                onShow={this.startShow}
            >
                <StatusBar barStyle='light-content' translucent={true} backgroundColor="rgba(16, 17, 22,0.75)" animated={false} />
                <TouchableOpacity
                    activeOpacity={1.0}
                    onPress={() => {

                    }}
                    style={styles.bottomcontainer}>
                    <StatusBar barStyle='light-content' translucent={true} backgroundColor="rgba(16, 17, 22,0.75)" animated={false} />
                    <View style={styles.container}>
                        <View style={styles.innerContainer}>

                            {
                                this.state.icon3 && (
                                    <Image
                                        source={{uri:this.state.icon3}}
                                        style={{ width: screen.PIXEL_270, height: screen.PIXEL_270,position:'absolute',opacity:0 }}
                                        onLoadEnd={()=>{

                                            this.haveusing.push(this.state.icon3);

                                            this.iconIndex = this.iconIndex + 1;
                                            if(this.icons[this.iconIndex]) {
                                                console.log('icon3',this.icons[this.iconIndex])
                                                this.setState({
                                                    icon3:this.icons[this.iconIndex]
                                                });
                                            }
                                        }}
                                    />
                                )
                            }
                            <View style={{ overflow: 'hidden', width: screen.PIXEL_400, height: screen.PIXEL_200, flexDirection: 'row', alignItems: 'center' ,marginTop:screen.PIXEL_40,
                            }}>

                                <Animated.Image
                                    source={ this.state.iconA1 ? {uri:this.state.iconA1} : this.state.icon1}
                                    style={{ width: screen.PIXEL_200, height: screen.PIXEL_200,position:'absolute',
                                        opacity: this.fadeAnim1,transform: [{ translateX: this.transX1 }]
                                    }}
                                />
                                <Animated.Image
                                    source={this.state.iconA2 ? {uri:this.state.iconA2} : this.state.icon2}
                                    style={{ width: screen.PIXEL_200, height: screen.PIXEL_200,position:'absolute',
                                        opacity: this.fadeAnim2,transform: [{ translateX: this.transX2 }] }}
                                />

                            </View>


                            <Text style={{ fontFamily:getffly("bold"), fontSize: 14, color: '#000',marginTop:screen.PIXEL_70 }}>{this.state.statetext1 + this.state.statetext2}</Text>
                            <View style={{ overflow: 'hidden', width: progressWidth , height: 6 , borderRadius: 3,backgroundColor:'#EEF3F0',marginTop:screen.PIXEL_30}}>
                                <View style={{width: progressWidth * this.state.progress , height: 6 , borderRadius: 3,backgroundColor:'#377C74'}}/>
                            </View>

                            <View style={{width:progressWidth,height: screen.PIXEL_40 ,flexDirection:'row',marginTop:screen.PIXEL_30,justifyContent:'space-between'}}>

                                <Text style={{fontFamily:getffly("bold"), fontSize: 14, color: showtips1 ? '#377C74' : '#A6A6A6'}}>{`1.${Constants.order.merchant_found}`}</Text>

                                <Image
                                    source={showtips1 ?  Images.choosed : Images.choose_no}
                                    style={styles.chooseImg }
                                />
                            </View>

                            <View style={{width:progressWidth, height: screen.PIXEL_40,flexDirection:'row',marginTop:10,justifyContent:'space-between'}}>
                                <Text style={{fontFamily:getffly("bold"), fontSize: 14, color: showtips2 ? '#377C74' : '#A6A6A6'}}>{`2.${Constants.order.product_matched}`}</Text>
                                <Image
                                    source={showtips2 ?  Images.choosed : Images.choose_no}
                                    style={styles.chooseImg }
                                />
                            </View>




                        </View>
                        <TouchableOpacity
                            style={{marginTop:screen.PIXEL_20}}
                            onPress={()=>{
                                this._setModalVisible(false)
                            }}
                        >
                            <Image source={Images.close} style={styles.close}/>
                        </TouchableOpacity>
                    </View>
                    {/*<Dialog ref={this.setDialogRef} />*/}
                </TouchableOpacity>
            </Modal>
        );
    }


    _setModalVisible = (visible) => {
        this.setState({ modalVisible: visible });
    }

    startShow = () => {

    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    innerContainer: {
        width: screen.width - screen.PIXEL_100,
        height:screen.scaleSize(730),
        backgroundColor: '#FFFFFF',
        justifyContent:'center',
        alignItems: 'center',
        borderRadius: screen.PIXEL_40
    },
    chooseImg:{
        width: screen.PIXEL_30,
        height: screen.PIXEL_30
    },
    close:{
        width:screen.PIXEL_70,
        height:screen.PIXEL_70
    },


    bottomcontainer: {
        zIndex: 2,
        flex: 1,
        alignItems: 'center',
        backgroundColor: 'rgba(16, 17, 22,0.75)',
        justifyContent: 'flex-end',
    },


});



export default Grabbing;
